package com.road.yishi.proto;

import java.io.IOException;

import org.apache.mina.core.buffer.IoBuffer;

import com.google.protobuf.CodedOutputStream;
import com.google.protobuf.Message;
import com.google.protobuf.AbstractMessage.Builder;

/**
 * 辅助类
 * 
 */
public class MessageUtil {

	/**
	 * 消息创建
	 * 
	 * @param code
	 * @param messageBuilder
	 * @return
	 */
	public static PBMessage buildMessage(short code, Builder<?> messageBuilder) {
		return buildMessage(code, messageBuilder.build());
	}

	/**
	 * 消息创建
	 * 
	 * @param code
	 * @param messageBuilder
	 * @return
	 */
	public static PBMessage buildMessage(short code, Message message) {
		PBMessage response = new PBMessage(code, -1);
		response.setMessage(message);
		return response;
	}

	/**
	 * 消息创建
	 * 
	 * @param code
	 * @param client
	 * @param messageBuilder
	 * @return
	 */
	public static PBMessage buildMessage(short code, int client, Builder<?> messageBuilder) {
		PBMessage response = new PBMessage(code, client);
		response.setMessage(messageBuilder.build());
		return response;
	}

	/**
	 * 消息创建
	 * 
	 * @param code
	 * @param client
	 * @return
	 */
	public static PBMessage buildMessage(short code, int client) {
		PBMessage message = new PBMessage(code, client);
		return message;
	}

	/**
	 * 数据包进行编码
	 * 
	 * @param message
	 * @return
	 * @throws IOException
	 */
	public static IoBuffer encode(PBMessage message) throws IOException {
		Message msg = message.getMessage();
		int size = 20 + msg.getSerializedSize(); // 数据长度
		IoBuffer buffer = IoBuffer.allocate(size);
		message.writeHeader(size, buffer); // 协议头部
		CodedOutputStream cos = CodedOutputStream.newInstance(buffer.asOutputStream());
		msg.writeTo(cos);
		cos.flush();
		return buffer;
	}
}
